//
//  WKPicClipViewController.m
//  Walk
//
//  Created by cesh on 16/9/26.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKPicClipViewController.h"

@interface WKPicClipViewController ()

@property (strong, nonatomic) UIImageView *picToClip;

@property (strong, nonatomic) UIView *clipView;

@end

@implementation WKPicClipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *clipView = [[UIView alloc]init];
    clipView.size = CGSizeMake(screenW, screenW);
    CGFloat upDownInset = (screenH - screenW) * 0.5;
    clipView.origin = CGPointMake(0, upDownInset);
    self.clipView = clipView;
    [self.view insertSubview:clipView atIndex:0];
    
    UIImageView *picToClip = [[UIImageView alloc]init];
    self.picToClip = picToClip;
    picToClip.frame = clipView.bounds;
    picToClip.contentMode = UIViewContentModeScaleAspectFit;
    picToClip.image = self.img;
    
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(picPinch:)];
    [picToClip addGestureRecognizer:pinch];

    picToClip.userInteractionEnabled = YES;
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(picPan:)];
    [picToClip addGestureRecognizer:pan];

    
    [self.clipView addSubview:picToClip];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)picPinch:(UIPinchGestureRecognizer *)pinch {
    pinch.view.transform = CGAffineTransformScale(pinch.view.transform, pinch.scale, pinch.scale);
    // 复位
    pinch.scale = 1.0f;
}

- (void)picPan:(UIPanGestureRecognizer *)pan {
        CGPoint transP = [pan translationInView:pan.view];
        pan.view.transform = CGAffineTransformTranslate(pan.view.transform, transP.x, transP.y);
        // 复位
        [pan setTranslation:CGPointZero inView:pan.view];
}

- (IBAction)cancel:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)select:(id)sender {
    
    
    // 绘制图片
    
    UIGraphicsBeginImageContextWithOptions(self.clipView.bounds.size, NO, 0);
    [self.clipView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *newImage =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //将裁减后的图片传回代理
    
    if ([self.delegate respondsToSelector:@selector(picClipViewController:clippedImage:)]) {
        [self.delegate picClipViewController:self clippedImage:newImage];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
